package com.hxzy.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 第一个Controller(它是servlet升级版)

 * @author tonneyyy
 */
//告诉spring，这一个mvc框架，servlet
@Controller
public class FirstController {

    /**
     * 方法编写，相当于重写  servlet中的doGet方法,url=/demo01/first
     * @return
     */
    @GetMapping(value = "/demo01")
    public ModelAndView   first(){
        ModelAndView  mv=new ModelAndView();
        mv.setViewName("demo01");
        return mv;
    }

    /**
     * 后台向前端转发数据   servlet中  request.setAttribute("键",Object值);
     * @return
     */
    @GetMapping(value = "/demo02")
    public ModelAndView   demo02(){
        ModelAndView  mv=new ModelAndView();
        mv.setViewName("demo02");
        mv.addObject("name","小张");
        mv.addObject("sex","男");
        mv.addObject("age",23);
        return mv;
    }

    /**
     * 后台接收前端的数据，向前端转发数据   servlet中  request.setAttribute("键",Object值);
     * @return
     */
    @GetMapping(value = "/demo03")
    public ModelAndView   demo03(Integer n){
        ModelAndView  mv=new ModelAndView();
        //参数有问题
        if(n==null || n<=0){
            mv.setViewName("error");
            return mv;
        }

        mv.setViewName("demo03");

        List<Map<String,Object>>  list=new ArrayList<>();
        for(int i=0;i<n;i++){
            Map<String,Object>  mp=new HashMap<>();
            mp.put("name","小张"+i);
            mp.put("sex", i%2==0?"男":"女");
            mp.put("age", 10+i);
            list.add(mp);
        }
        mv.addObject("data", list);

        return mv;
    }

    // 路径表达式 restful
    @GetMapping(value = "/demo03/{number}")
    public ModelAndView   demo04( @PathVariable(value = "number") Integer n){
        ModelAndView  mv=new ModelAndView();
        //参数有问题
        if(n==null || n<=0){
            mv.setViewName("error");
            return mv;
        }

        mv.setViewName("demo03");

        List<Map<String,Object>>  list=new ArrayList<>();
        for(int i=0;i<n;i++){
            Map<String,Object>  mp=new HashMap<>();
            mp.put("name","小张"+i);
            mp.put("sex", i%2==0?"男":"女");
            mp.put("age", 10+i);
            list.add(mp);
        }
        mv.addObject("data", list);

        return mv;
    }



}
